window.onload = function(){
	//禁止ios手机双击滑动页面
	(function()
	{
	    var agent = navigator.userAgent.toLowerCase();        //检测是否是ios
	    var iLastTouch = null;                                //缓存上一次tap的时间
	    if (agent.indexOf('iphone') >= 0 || agent.indexOf('ipad') >= 0)
	    {
	        document.body.addEventListener('touchend', function(event)
	        {
	            var iNow = new Date()
	                .getTime();
	            iLastTouch = iLastTouch || iNow + 1 /** 第一次时将iLastTouch设为当前时间+1 */ ;
	            var delta = iNow - iLastTouch;
	            if (delta < 500 && delta > 0)
	            {
	                event.preventDefault();
	                return false;
	            }
	            iLastTouch = iNow;
	        }, false);
	    }
	})();
	//禁止页面上下滑动-ios橡皮筋效果
//	document.body.addEventListener("touchmove",function(event){
//	    event.preventDefault();
//	},{passive: false});
	//需要滚动的元素设置滚动
	var ruleEl = document.querySelector(".ruleContent")//你需要滑动的dom元素
	var rankEl = document.querySelector(".rankContent")//你需要滑动的dom元素
    iosTrouchFn(ruleEl);
    iosTrouchFn(rankEl);
	function iosTrouchFn(el) {
	    //el需要滑动的元素
	    el.addEventListener('touchmove',function(e){
	        e.isSCROLL = true;
	    })
	    document.body.addEventListener('touchmove',function(e){
	        if(!e.isSCROLL){
	            e.preventDefault(); //阻止默认事件(上下滑动)
	        }else{
	            //需要滑动的区域
	            var top = el.scrollTop; //对象最顶端和窗口最顶端之间的距离 
	            var scrollH = el.scrollHeight; //含滚动内容的元素大小
	            var offsetH = el.offsetHeight; //网页可见区域高
	            var cScroll = top + offsetH; //当前滚动的距离
	 
	            //被滑动到最上方和最下方的时候
	            if(top == 0){
	                top = 1; //0～1之间的小数会被当成0
	            }else if(cScroll === scrollH){
	                  el.scrollTop = top - 0.1;
	            }
	        }
	    }, {passive: false}) //passive防止阻止默认事件不生效
	}

	//预加载
	function reload(){
		//实例化一个预加载资源的对象
		var queue = new createjs.LoadQueue();
		var angle = 0;
		var leftContent = document.querySelector(".left-content");
		var rightContent = document.querySelector(".right-content");
		var textCircle = document.querySelector(".text-circle");
		let reloadPage = document.querySelector(".reload");
		//设置加载的资源
		queue.loadManifest([{
			"id": 1,
			"src": "img/Mc_world1.jpg"
		},
		{
			"id": 2,
			"src": "img/Mc_world2.jpg"
		},
		{
			"id": 3,
			"src": "img/Mc_world3.jpg"
		},
		{
			"id": 4,
			"src": "img/Mc_world4.jpg"
		},
		{
			"id": 5,
			"src": "img/Mc_player8.png"
		},
		{
			"id": 6,
			"src": "media/10097.mp3"
		}
		]);
		queue.on("progress", function(res) {
			//console.log("progress", res);
			angle = 360 * res.progress;
			if(angle > 180) {
				leftContent.setAttribute('style', 'transform: rotate(' + (angle - 180) + 'deg)');
				rightContent.setAttribute('style', 'transform: rotate( 180deg )');
			} else {
				rightContent.setAttribute('style', 'transform: rotate(' + angle + 'deg)');
			}
			//loading.innerText = Math.floor(res.progress * 100) + "%";
			textCircle.innerText = parseInt(res.progress * 100) + '%';
		})
		queue.on("complete", function(res) {
			//console.log("complete", res);
			reloadPage.style.display = "none";
		})
	}
	reload();
	var screenWidth = $(window).width();
	var bgTimer,roadTimer,lifeTimer;
	var lifeTime = 3;
	var totalScore = 0;
	var lifeDiv = "<div class='lifeItem'><img src='img/Mc_heart.png'/></div>";
	//背景移动
	function bgMove(){
		var totalWidth = $(".gamebgImg img").eq(0).width()*4;
		var curWidth = 0;
		bgTimer = setInterval(function(){
			curWidth-=0.6;
			//$(".gamebg").attr("transtion","1s linear");
			$(".gamebg").css({
				"transform":"translate3d("+ curWidth +"px,0,0)"
			})
			if(curWidth <= -totalWidth){
				curWidth = 0;
				$(".gamebg").removeAttr("style");
			}
		},1000/60)
	}
	console.log($(".road").eq(0).find(".roadGift"));
	//道路移动
	function roadMove(idx){
		//随机生成奖品
		$(".road").eq(idx).find(".roadGift").remove();
		$(".road").eq(idx).find(".roadStone").remove();
		for(var i=1; i<4; i++){
			var giftDiv = "";
			var giftNum = Math.floor(Math.random()*7+1);
			if(giftNum == 1){
				giftDiv = "<div class='roadStone element' data-gift=1 style='top:-30px;"+"left:"+(i*50)+"px;' ><img src='img/Mc_prop"+ giftNum +".png'/></div>";
				$(".road").eq(idx).append(giftDiv);
			}else{
				var giftHeight = -(Math.floor(Math.random()*101+200));
				if(giftNum == 7){
					giftDiv = "<div class='roadGift element' data-gift=3 style='top:"+giftHeight+"px;left:"+((i-1)*125)+"px;'><img src='img/Mc_prop"+ giftNum +".png'/></div>";
					$(".road").eq(idx).append(giftDiv);
				}else{
					giftDiv = "<div class='roadGift element' data-gift=2 style='top:"+giftHeight+"px;left:"+((i-1)*125)+"px;'><img src='img/Mc_prop"+ giftNum +".png'/></div>";
					$(".road").eq(idx).append(giftDiv);
				}
			}
		}
		$(".road").eq(idx).css("left",screenWidth);
		$(".road").eq(idx).stop();
		//随机生成道路的高度
		var roadHeight = Math.floor(Math.random()*151+350);
		$(".road").eq(idx).css("top",roadHeight);
		$(".road").eq(idx).animate({
			left:-(screenWidth)
		},{
		    easing: 'linear',
		    duration: 3000
		});
	}
	//两个道路横杠交替
	function roadControl(){
		var  roadNum = 1;
		roadTimer = setInterval(function(){
			if(roadNum == 0){
				roadNum = 1;
				roadMove(roadNum);
			}else{
				roadNum = 0;
				roadMove(roadNum);
			}
		},2500)
	}
	
	
	//礼物碰撞检测
	function collision(obj1,obj2){
		let obj1Pos = obj1.getBoundingClientRect();
		let obj2Pos = obj2.getBoundingClientRect();
		let t1 = obj1Pos.top,
			r1 = obj1Pos.right,
			b1 = obj1Pos.bottom,
			l1 = obj1Pos.left;
		let t2 = obj2Pos.top,
			r2 = obj2Pos.right,
			b2 = obj2Pos.bottom,
			l2 = obj2Pos.left;
		if(t1>b2||r1<l2||b1<t2||l1>r2){
			return false;
		}else{
			return true;
		}
	}
	//横杠碰撞检测
	function roadCollision(obj1,obj2){
		let obj1Pos = obj1.getBoundingClientRect();
		let obj2Pos = obj2.getBoundingClientRect();
		let t1 = obj1Pos.top,
			r1 = obj1Pos.right,
			b1 = obj1Pos.bottom,
			l1 = obj1Pos.left;
		let t2 = obj2Pos.top,
			r2 = obj2Pos.right,
			b2 = obj2Pos.bottom,
			l2 = obj2Pos.left;
		if(t1+90>b2||r1-20<l2||b1<t2||l1+20>r2){
			return false;
		}else{
			return true;
		}
	}
	//跳跃
	var jumpTime = 0;
	var isJump = true;
	function jump(){
		$(window).on("touchend",function(){
			jumpTime++;
			if(jumpTime>2){
				isJump = false;
			}
			if(isJump){
				if($(".people").is(":animated") ){ //判断元素是否处于动画状态
					$(".people").stop(true,false);
				}
				$(".people").removeClass("run");
				$(".people").removeClass("roll");
				$(".people").animate({
					top:$(".people").offset().top-150
				},{
				    easing: 'easeOutQuint',
				    duration: 400
				});
				down();
			}
		})
	}
	//掉落
	var player = document.querySelector(".people");
	function down(){
		$(".people").removeClass("run roll");
		$(".people").animate({
			top:$(window).height()
		},{
		    easing: 'easeInQuad',
		    duration: 1000,
		    step: function(now,fx){
		    	//从上面下落初始化跳跃条件
		    	if(fx.now<0 && jumpTime==0){
					isJump = true;
		    	}
		    	//判断是否碰到横杠
				var road = document.querySelectorAll(".road");
				var isRun1 = roadCollision(player,road[0]),
					isRun2 = roadCollision(player,road[1]);
				if(isRun1){
					$(".people").stop(true,false).addClass("run");
					fx.now = $(".roadItem").eq(0).offset().top-100;
					//console.log(fx.now);
					//判断再次可以跳跃
					isJump = true;
					jumpTime = 0;
					//判断横杠超过人之后开始跌落
					var runDown = setInterval(function(){
						if($(".roadItem").eq(0).offset().left<-210){
							//移除滚动和开始可以跳跃
							if($(".people").hasClass("roll")){
								jump();
								$(".people").removeClass("roll");
							}
							$(".people").removeClass("run");
							$(".people").animate({
								top:$(window).height()
							},{
								easing: 'easeInQuad',
			    				duration: 800
							});
							clearInterval(runDown);
						}
					})
				}
				if(isRun2){
					$(".people").stop(true,false).addClass("run");
					fx.now = $(".roadItem").eq(1).offset().top-100;
					//console.log(fx.now);
					//判断再次可以跳跃
					isJump = true;
					jumpTime = 0;
					var runDown = setInterval(function(){
						if($(".roadItem").eq(1).offset().left<-210){
							//移除滚动和开始可以跳跃
							if($(".people").hasClass("roll")){
								jump();
								$(".people").removeClass("roll");
							}
							$(".people").removeClass("run");
							$(".people").animate({
								top:$(window).height()
							},{
								easing: 'easeInQuad',
			    				duration: 800
							});
							clearInterval(runDown);
						}
					})
				}
		    }
		});
	}
	//分数计算
	var bumpTime1 = 0,
		bumpTime2 = 0,
		bumpTime3 = 0,
		bumpTime4 = 0,
		bumpTime5 = 0,
		bumpTime6 = 0;
	//障碍物碰撞检测
	function bumpTesting(){
		var allElement = document.querySelectorAll(".element");
		var isBump1 = collision(player,allElement[0]),
			isBump2 = collision(player,allElement[1]),
			isBump3 = collision(player,allElement[2]),
			isBump4 = collision(player,allElement[3]),
			isBump5 = collision(player,allElement[4]),
			isBump6 = collision(player,allElement[5]);
		if(isBump1){
			bumpTime1++;
			if(bumpTime1 == 1){
				var ele = allElement[0];
				var idx = allElement[0].dataset.gift;
				selScore(idx,ele);
			}
		}else{
			bumpTime1 = 0;
		}
		if(isBump2){
			bumpTime2++;
			if(bumpTime2 == 1){
				var ele = allElement[1];
				var idx = allElement[1].dataset.gift;
				selScore(idx,ele);
			}
		}else{
			bumpTime2 = 0;
		}
		if(isBump3){
			bumpTime3++;
			if(bumpTime3 == 1){
				var ele = allElement[2];
				var idx = allElement[2].dataset.gift;
				selScore(idx,ele);
			}
		}else{
			bumpTime3 = 0;
		}
		if(isBump4){
			bumpTime4++;
			if(bumpTime4 == 1){
				var ele = allElement[3];
				var idx = allElement[3].dataset.gift;
				selScore(idx,ele);
			}
		}else{
			bumpTime4 = 0;
		}
		if(isBump5){
			bumpTime5++;
			if(bumpTime5 == 1){
				var ele = allElement[4];
				var idx = allElement[4].dataset.gift;
				selScore(idx,ele);
			}
		}else{
			bumpTime5 = 0;
		}
		if(isBump6){
			bumpTime6++;
			if(bumpTime6 == 1){
				var ele = allElement[5];
				var idx = allElement[5].dataset.gift;
				selScore(idx,ele);
			}
		}else{
			bumpTime6 = 0;
		}
	}
	var bumpTimer = setInterval(bumpTesting,100);
	//判断分数类型
	function selScore(idx,ele){
		switch(idx){
			case "1":
				//滚动和禁止跳跃
				$(".people").addClass("roll");
				$(window).off("touchend");
				break;
			case "2":
				totalScore+=1;
				break;
			case "3":
				totalScore+=5;
				break;
		}
		$(".score").text(totalScore);
		ele.style.transition = "1s";
		ele.style.transform = "scale(0)";
		ele.style.opacity = "0.1";
	}
	//生命计算
	function lifeControl(){
		if(lifeTime<=0){
			clearInterval(lifeTimer);
			isJump = false;
    		$(".road").eq(0).stop();
    		$(".road").eq(1).stop();
    		$(window).off("touchend");
    		clearInterval(bgTimer);
			clearInterval(roadTimer);
			//弹出结束页面
			$(".finishPage").fadeIn();
			$(".endScore").text(totalScore);
			$(".firstRoad").css("left",0);
		}
		if($(".people").offset().top >= $(window).height()-10){
			isJump = false;
			lifeTime-=1;
			$(".lifeItem").remove();
			for(var i=0; i<lifeTime; i++){
				$(".life").append(lifeDiv);
			}
			if(lifeTime>0){
				//设置小人高度为0
				$(".people").stop(true,false);
				$(".people").css("top","-100px");
				jumpTime = 0;
				down();
			}
		}
	}
	//开始游戏
	function startGame(){
		//初始化参数
		$(".people").removeClass("roll");
		lifeTime = 3;
		isJump = true;
		jumpTime = 0;
		totalScore = 0;
		$(".people").css({
			"top":300,
			"left":-80
		}).addClass("run").animate({
			left: 80
		},{
		    easing: 'linear',
		    duration: 1500
		})
		$(".road").eq(0).css({
			top:400,
			left:500
		});
    	$(".road").eq(1).css({
			top:400,
			left:500
		});
		$(".score").text("0");
		for(var i=0; i<lifeTime; i++){
			$(".life").append(lifeDiv);
		}
		$(".gamebg").css("transform","translate3d(0,0,0)");
		setTimeout(function(){
			$(".firstRoad").animate({
				left: -350
			},{
			    easing: 'linear',
			    duration: 2500,
			    step:function(now,fx){
			    	if(fx.now<-210){
			    		down();
			    	}
			    }
			});
			bgMove();
			roadControl();
			jump();
		},1500)
		lifeTimer = setInterval(lifeControl,1000);
	}
	let bgMusic = document.getElementById('bgmusic');
	let musicBtn = document.querySelector(".musicLogo");
	//控制音乐
	function musicControl(){
		musicBtn.style.left = screenWidth*0.9 + "px";
		musicBtn.addEventListener("click",function(){
			if(bgMusic.paused){
				bgMusic.play();
				musicBtn.children[0].src = "img/Btn_sound1.png";
				musicBtn.classList.add("musicRotate");
			}else{
				bgMusic.pause();
				musicBtn.children[0].src = "img/Btn_sound2.png";
				musicBtn.classList.remove("musicRotate");
			}
		})
	}
	musicControl();
	//页面按钮控制
	//点击开始按钮开始游戏
	$(".play").on("touchend",function(){
		$(".index").css("display","none");
		startGame();
		if(bgMusic.paused){
			bgMusic.play();
			musicBtn.children[0].src = "img/Btn_sound1.png";
			musicBtn.classList.add("musicRotate");
		}else{
			bgMusic.pause();
			musicBtn.children[0].src = "img/Btn_sound2.png";
			musicBtn.classList.remove("musicRotate");
		}
	})
	//点击分享按钮弹出提示页
	$(".share").on("touchend",function(){
		$(".sharePage").fadeIn();
		
	})
	$(".sharePage").on("touchend",function(){
		$(".sharePage").css("display","none");
	})
	//再玩一次按钮
	$(".rePlay").on("touchend",function(){
		$(".finishPage").css("display","none");
		startGame();
	})
	//游戏规则
	$(".gameRule").on("touchend",function(){
		$(".rulePage").fadeIn();
	})
	//查看排名
	$(".ruleRank").on("touchend",function(){
		$(".rulePage").fadeOut();
		$(".rankPage").fadeIn();
	})
	//go按钮开始游戏
	$(".ruleStart").on("touchend",function(){
		$(".rulePage").css("display","none");
		$(".index").css("display","none");
		startGame();
	})
	//游戏规则关闭
	$(".ruleClose").on("touchend",function(){
		$(".rulePage").fadeOut();
	})
	//获奖名单
	$(".prizeList").on("touchend",function(){
		$(".rankPage").fadeIn();
	})
	//获奖名单关闭
	$(".rankClose").on("touchend",function(){
		$(".rankPage").fadeOut();
	})
	//查看排名
	$(".ranking").on("touchend",function(){
		$(".rankPage").fadeIn();
	})
};